<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="dd">
    <!--器材提示框-->
    <div class="scene_tips" v-if="false" :style="getPosition">
      <!-- <img src="@/images/scene_tips.png" class="img_back" /> -->
      <div class="scene_tipsall">{{ tipName }}</div>
    </div>
    <!-- 文字提示框 -->
    <!-- 注意事项 -->
    <!-- 电子天平数显 -->
  </div>
</template>
<script>
import { mixins } from '@/mixin/three'

export default {
  mixins: [mixins], //混入
  components: {},
  props: {
    step: Number,
    steps: Number,
    myshow: Boolean,
    loading: Boolean
  },
  // components: { tipError },
  data() {
    return {
      isPointerLocked: false,
      cameraMoveSensitivity: 0.4, //视角灵敏度
      leftMouseBtn: false,
      baseURL: 'https://zfatt.oss-cn-beijing.aliyuncs.com/experiment/dr/',
      objectReItem: null,
      time: null,
      studyshow: false,
      action: null,
      andh: null,
      jcname: '',
      tipErrorShow: false,
      name: '', //标题名称
      info: '', //标题信息
      i: 1, //相机轨道控制器兼容性问题处理
      // step: 1, //步骤处理
      selectedObjects: [],
      tipPosition: {}, //图标位置
      tipName: null, //提示名字
      tipShow: false,
      playIng: false,
      camera: null,
      scene: null,
      render: null,
      raycaster: null,
      mouse: null,
      objects: [],
      objectFather: null,
      //鼠标放上会变成手，并且显示提示气泡
      objectNames: [
        'XianShuChuiZhiCeShiTong_1', //
        'ZhunZhiDuJianCeBan',
        'PingBanTanCeQi',
        'CT1_7',
        'ZhuoZI2_2',
        'DR4'
      ],
      //气泡对应名称
      objectText: [
        { name: 'XianShuChuiZhiCeShiTong_1', text: '圆柱体' },
        { name: 'ZhunZhiDuJianCeBan', text: '检测板' },
        { name: 'PingBanTanCeQi', text: '平板探测器' },
        { name: 'ZhuoZI2_2', text: '电脑' },
        { name: 'DR4', text: '床' }
      ],
      dhfiles: [],
      zoomSpeed: 1,
      prevTime: new Date().getTime(),
      moveForward: false,
      moveLeft: false,
      moveBackward: false,
      moveRight: false,
      canJump: false,
      playerOnFloor: false,
      GRAVITY: 30,
      keyStates: {},

      cameraOriginal: [-4.51, 1.456, 0.574],
      cameraLookAt: [-4.51, 1.456, 0.674]
      //    cameraOriginal: [-21.478, 1.586, -6.288],
      // cameraLookAt: [-21.478, 1.586, -6.088]
    }
  },
  mounted() {
    this.init()

    // 在这里添加鼠标指针锁定状态的监听
    document.addEventListener(
      'pointerlockchange',
      this.handlePointerLockChange,
      false
    )
    document.addEventListener(
      'mozpointerlockchange',
      this.handlePointerLockChange,
      false
    )
    document.addEventListener(
      'webkitpointerlockchange',
      this.handlePointerLockChange,
      false
    )
  },
  beforeDestroy() {
    // 在组件销毁前移除事件监听
    document.removeEventListener(
      'pointerlockchange',
      this.handlePointerLockChange,
      false
    )
    document.removeEventListener(
      'mozpointerlockchange',
      this.handlePointerLockChange,
      false
    )
    document.removeEventListener(
      'webkitpointerlockchange',
      this.handlePointerLockChange,
      false
    )
    // document.removeEventListener('keydown', false)
    // document.removeEventListener('keyup', false)
  },
  watch: {
    //监听大步骤
    step(item) {
      // this.stopAndReleaseAnimations()
      console.log('小步骤值：' + item)
      this.andh = null
      clearTimeout(this.time)
      if (this.action) {
        this.action.stop()
      }
      this.action = null
      this.setp = this.setps

      // if (item == 2) {
      //   this.initFileS(0)
      // }
    },
    steps(item) {
      console.log(item)
      this.setp = this.setps
    },
    myshow(item) {
      if (!item) {
        this.camera.rotation.order = 'XYZ'
        this.camera.lookAt(0, 0, 0)
        // this.camera = this.cameras
        this.move(
          [-1.696, 1.369, -3.11],
          [-175.59 / 180, 4.87 / 180, 179.62 / 180]
        )
        document.exitPointerLock()
      }
      if (item) {
        // 漫游镜头控制
        document.body.requestPointerLock()
        if (document.pointerLockElement !== null) {
          document.exitPointerLock()
        }
        // 鼠标左键被点击
        this.leftMouseBtn = true
        this.camera.rotation.order = 'YXZ'

        this.camera.lookAt(
          this.cameraLookAt[0],
          this.cameraLookAt[1],
          this.cameraLookAt[2]
        )
      }
    },
    isPointerLocked(newValue) {
      if (newValue) {
        this.$emit('myshowfn', true)
        document.addEventListener('keydown', (event) => {
          this.keyStates[event.code] = true
        })
        document.addEventListener('keyup', (event) => {
          this.keyStates[event.code] = false
        })
        // 在这里执行你的操作
      } else {
        // 鼠标指针未锁定，执行相关操作
        this.$emit('myshowfn', false)

        // 在这里执行你的操作
      }
    }
  },

  methods: {
    handlePointerLockChange() {
      // 更新数据，触发 watch
      this.isPointerLocked = this.checkPointerLock()
    },
    checkPointerLock() {
      return (
        document.pointerLockElement === document.body ||
        document.mozPointerLockElement === document.body ||
        document.webkitPointerLockElement === document.body
      )
    },
    //根据点击的模型播放动画
    clickAfter(realName) {
      if (
        (realName == 'PingBanTanCeQi' || realName == 'DR4') &&
        this.step == 2
      ) {
        this.$emit('clickItem', 'PingBanTanCeQi')
        console.log('执行')
      }
      if (
        (realName == 'ZhunZhiDuJianCeBan' || realName == 'DR4') &&
        this.step == 2
      ) {
        this.$emit('clickItem', 'ZhunZhiDuJianCeBan')
        console.log('执行')
      }
      if (realName == 'ZhuoZI2_2' && this.step == 5) {
        this.$emit('clickItem', 'ZhuoZI2_2')
      }
      console.log(
        '点击了模型',
        realName,
        '当前大步骤',
        this.step,
        '当前小步骤',
        this.steps
      )
      this.twinklePoint(-3, -3, -3)
      // 动画还没加载完的情况
      if (!this.andh) {
        if (this.action) {
          this.action.stop()
          this.action.paused = true
        }
        this.action = null
        return
      }
      if (this.playIng) {
        // this.step
        if (!this.playIng) {
          console.log('当前任务还未完成禁止下一个')
        } else {
          return
        }
      }
      let animationName = ''

      //  正确第一步
      if (realName == 'CT3' && this.step == 2 && this.steps == 1) {
        animationName = 'All Animations'
        // this.$emit('audo', require('@/images/audios/pz02.mp3'))
      }

      if (!animationName) {
        console.log('返回空 ')
        return
      }
      this.clearPoint()
      this.playAction(animationName, realName)
    },
    getRealName(object) {
      //根据模型返回其父级group的名称，且之后在objects中存在的才会返回名称
      let objectNames = this.objectNames
      if (objectNames.includes(object.name)) {
        return object.name
      } else {
        if (object.parent) {
          return this.getRealName(object.parent)
        } else {
          return ''
        }
      }
    },
    onDocumentMouseMove(event) {
      // 相机移动视角
      // 鼠标左键拖动时移动视角
      if (document.pointerLockElement === document.body && this.myshow) {
        this.camera.rotation.x -= event.movementY / 500
        this.camera.rotation.y -= event.movementX / 500
      }

      // if (this.leftMouseBtn && this.myshow) {
      //   this.camera.rotation.x -= event.movementY / 2000
      //   this.camera.rotation.y -= event.movementX / 2000
      // }
      //鼠标移动，用射线检测鼠标覆盖的东西，并弹出标识
      let maincontWidth = this.$el.offsetWidth
      let maincontHeight = this.$el.offsetHeight
      this.mouse.x = (event.offsetX / maincontWidth) * 2 - 1
      this.mouse.y = -(event.offsetY / maincontHeight) * 2 + 1
      this.raycaster.setFromCamera(this.mouse, this.camera)
      const intersections = this.raycaster.intersectObjects(this.objects)
      if (intersections.length > 0) {
        document.body.style.cursor = 'pointer'
        let textName = this.getTextName(
          this.getRealName(intersections[0].object)
        )
        this.tipShow = true
        this.tipPosition = {
          x: event.offsetX,
          y: event.offsetY
        }
        this.tipName = textName
      } else {
        document.body.style.cursor = 'initial'
        this.tipShow = false
        this.tipPosition = {
          x: event.offsetX,
          y: event.offsetY
        }
        this.tipName = ''
        this.selectedObjects = []
      }
    }, //鼠标按下播放动画
    onDocumentMouseDown(event) {
      // event.preventDefault()
      //鼠标移动，用射线检测鼠标覆盖的东西，并弹出标识

      let maincontWidth = this.$el.offsetWidth
      let maincontHeight = this.$el.offsetHeight
      this.mouse.x = (event.offsetX / maincontWidth) * 2 - 1
      this.mouse.y = -(event.offsetY / maincontHeight) * 2 + 1
      this.raycaster.setFromCamera(this.mouse, this.camera)
      const intersections = this.raycaster.intersectObjects(this.objects)
      if (intersections.length > 0) {
        document.body.style.cursor = 'pointer'
        if (intersections[0].object.name == this.jcname) {
          // this.addOutinesss('')
          document.exitPointerLock()
        }
        this.clickAfter(intersections[0].object.name)
      }

      // if (event.button == 0 && this.myshow) {
      //   event.preventDefault()
      //   // 鼠标左键被点击
      //   this.leftMouseBtn = true
      //   this.camera.rotation.order = 'YXZ'

      //   this.camera.lookAt(
      //     this.cameraLookAt[0],
      //     this.cameraLookAt[1],
      //     this.cameraLookAt[2]
      //   )
      // }
      if (document.pointerLockElement && !this.myshow) {
        event.preventDefault()
      } else {
        // if (
        //   this.myshow &&
        //   event.target.localName == 'canvas' &&
        //   !document.pointerLockElement
        // ) {
        //   // 漫游镜头控制
        //   document.body.requestPointerLock()
        //   // 鼠标左键被点击
        //   this.leftMouseBtn = true
        //   this.camera.rotation.order = 'YXZ'
        //   this.camera.lookAt(
        //     this.cameraLookAt[0],
        //     this.cameraLookAt[1],
        //     this.cameraLookAt[2]
        //   )
        // }
      }
    },
    // onDocumentMouseUp(event) {
    //   event.preventDefault()
    //   if (event.button == 0) {
    //     // 鼠标左键抬起
    //     this.leftMouseBtn = false
    //   }
    // },
    //按照坐标位置显示指示箭头
    twinklePoint(x, y, z) {
      if (this.sprite) {
        this.sprite.visible = true
        this.sprite.position.set(x, y, z)
        this.spriteTimer = setInterval(() => {
          this.sprite.visible = !this.sprite.visible
        }, 600)
      }
    }, //清除指示箭头
    clearPoint() {
      if (this.sprite) {
        this.sprite.visible = false
      }
      if (this.spriteTimer) {
        clearInterval(this.spriteTimer)
        this.spriteTimer = null
      }
    },
    //物品描边提示步骤
    addOutinesss(name) {
      this.jcname = name
      let array = []
      array = this.objects.filter((item) => {
        if (item.name == name) {
          return item
        }
      })
      this.outlinePass.selectedObjects = array
    },

    getTextName(realName) {
      //根据模型名称返回对应汉字
      let textName = ''
      this.objectText.map((item) => {
        if (item.name == realName) {
          textName = item.text
        }
      })
      return textName
    },

    //镜头移动视角切换根据不同的步骤进行操作
    move(position, rotation) {
      // this.controls.enabled = false
      this.camera.position.set(position[0], position[1], position[2])
      this.camera.rotation.set(
        rotation[0] * Math.PI,
        rotation[1] * Math.PI,
        rotation[2] * Math.PI
      )
      this.camera.updateProjectionMatrix()
    }
  }
}
</script>
<style>
.dd {
  height: 100%;
}
.mykg {
  position: absolute;
  top: 30%;
  right: 20%;
  color: red;
  cursor: pointer;
  border: solid 1px red;
}
.qdan {
  z-index: 1000;
  position: absolute;
  top: 110px;
  left: calc(50% - 80px);
  cursor: pointer;
}
</style>
